package volcengine

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"time"

	"gitee.com/zhyclouds/fable-scribe/internal/domain"
	"gitee.com/zhyclouds/fable-scribe/internal/service/text"
	"github.com/spf13/viper"
)

// VolcengineTextService 火山方舟文本生成服务
type VolcengineTextService struct {
	baseURL string
	apiKey  string
	client  *http.Client
}

// NewVolcengineTextService 创建火山方舟文本服务实例
func NewVolcengineTextService() text.Service {
	apikey := viper.GetString("ARK_API_KEY")
	if apikey == "" {
		panic("未读取到 openai-key")
	}

	return &VolcengineTextService{
		baseURL: "https://ark.cn-beijing.volces.com/api/v3",
		apiKey:  apikey,
		client: &http.Client{
			Timeout: time.Second * 60 * 10, // 增加超时时间到60秒
		},
	}
}

// 火山方舟API请求结构
type volcengineChatRequest struct {
	Model    string                  `json:"model"`
	Messages []volcengineChatMessage `json:"messages"`
}

type volcengineChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

// 火山方舟API响应结构
type volcengineChatResponse struct {
	Choices []struct {
		Message struct {
			Content string `json:"content"`
		} `json:"message"`
	} `json:"choices"`
}

// GenerateText 实现文本生成功能
func (s *VolcengineTextService) GenerateText(ctx context.Context, req domain.TextGenerationRequest) (domain.TextGenerationResponse, error) {
	// 参数验证
	if req.Prompt == "" {
		return domain.TextGenerationResponse{}, errors.New("prompt不能为空")
	}

	// 如果没有指定模型ID，使用默认的doubao-seed-1-6-251015
	modelID := req.ModelID
	if modelID == "" {
		modelID = "doubao-seed-1-6-251015"
	}

	// 构建消息列表
	messages := []volcengineChatMessage{
		{
			Role:    "user",
			Content: req.Prompt,
		},
	}

	// 构建API请求
	apiReq := volcengineChatRequest{
		Model:    modelID,
		Messages: messages,
	}

	reqBody, err := json.Marshal(apiReq)
	if err != nil {
		return domain.TextGenerationResponse{}, fmt.Errorf("序列化请求体失败: %w", err)
	}

	// 创建HTTP请求，使用传入的context
	httpReq, err := http.NewRequestWithContext(ctx, "POST", s.baseURL+"/chat/completions", bytes.NewBuffer(reqBody))
	if err != nil {
		return domain.TextGenerationResponse{}, fmt.Errorf("创建请求失败: %w", err)
	}

	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("Authorization", "Bearer "+s.apiKey)

	// 发送请求
	resp, err := s.client.Do(httpReq)
	if err != nil {
		return domain.TextGenerationResponse{}, fmt.Errorf("发送请求失败: %w", err)
	}
	defer resp.Body.Close()

	// 读取响应
	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return domain.TextGenerationResponse{}, fmt.Errorf("读取响应失败: %w", err)
	}

	// 检查响应状态
	if resp.StatusCode != http.StatusOK {
		return domain.TextGenerationResponse{}, fmt.Errorf("API返回错误状态码: %d, 响应: %s", resp.StatusCode, string(respBody))
	}

	// 解析响应
	var apiResp volcengineChatResponse
	if err := json.Unmarshal(respBody, &apiResp); err != nil {
		return domain.TextGenerationResponse{}, fmt.Errorf("解析响应失败: %w", err)
	}

	// 验证响应数据
	if len(apiResp.Choices) == 0 || apiResp.Choices[0].Message.Content == "" {
		return domain.TextGenerationResponse{}, errors.New("API返回空内容")
	}

	// 返回结果
	return domain.TextGenerationResponse{
		Content: apiResp.Choices[0].Message.Content,
	}, nil
}
